<template>
  <div class="app-container flex column">
    <!-- 场所管理-场所分类 -->
    <top-title :content="content" :updateTime="true"></top-title>
    <div class="tree-from-wrap f1 flex m-h-0">
      <div class="left-tree-wrap bg-common-card f1 m-h-0 flex column">
        <!-- 按钮 -->
        <div class="btn-group flex">
          <div class="btn-common" @click="handleAdd()">添加下级</div>
          <!-- <div class="btn-common">批量删除</div> -->
        </div>

        <!-- 提醒 -->
        <div class="alter flex align-center">
          <img alt="" src="@/assets/imgs/alter_icon.png" />
          <span>当前选择:</span>
          <span v-if="currSelected.id">{{ currSelected.informationName }}</span>
          <span v-if="currSelected.id" @click="onClearSelected">取消选择</span>
        </div>

        <div class="search-group" style="padding: 0 0.1rem 0 0.2rem">
          <div class="input-wrap" style="width: 100%">
            <div class="input-item" style="padding: 0; width: 100%">
              <a-input v-model="value" :maxLength="15" placeholder="请输入分类名称" @pressEnter="onSearch">
                <a-icon slot="prefix" class="search-icon" type="search" />
                <a-button slot="suffix" class="searchBtn" style="margin-right: 0" type="primary" @click="onSearch"
                  >搜索</a-button
                >
              </a-input>
            </div>
          </div>
        </div>

        <div class="tree-wrap f1 m-h-0">
          <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
            <a-tree
              :autoExpandParent="autoExpandParent"
              :checkStrictly="checkStrictly"
              :checkedKeys="checkedKeys"
              :expandedKeys="iExpandedKeys"
              :loading="loading"
              :replace-fields="replaceFields"
              :selectedKeys="selectedKeys"
              :treeData="departTree"
              checkable
              multiple
              @check="onSelect"
              @expand="onExpand"
              @rightClick="rightHandle"
              @select="onSelect"
            >
              <a-icon slot="switcherIcon" type="down" />
              <template #title="{ informationName }">
                <span v-if="informationName.indexOf(value) > -1">
                  {{ informationName.substr(0, informationName.indexOf(value)) }}
                  <span style="color: #ecf0f1; background: #74b9ff">{{ value }}</span>
                  {{ informationName.substr(informationName.indexOf(value) + value.length) }}
                </span>
                <span v-else>{{ informationName }}</span>
              </template>
            </a-tree>
            <!--新增右键点击事件,和增加添加和删除功能-->
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="handleAdd(2)">添加</a-menu-item>
              <a-menu-item key="2" @click="handleDelete">删除</a-menu-item>
              <a-menu-item key="3" @click="closeDrop">取消</a-menu-item>
            </a-menu>
          </a-dropdown>

          <div class="drawer-bootom-button">
            <a-dropdown :trigger="['click']" placement="topCenter">
              <a-menu slot="overlay" class="much">
                <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
                <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
              </a-menu>
              <a-button class="searchBtn"> 树操作 <a-icon type="up" /> </a-button>
            </a-dropdown>
          </div>
        </div>
      </div>

      <div class="right-form-wrap bg-common-card f1 m-h-0">
        <a-card v-if="selectedKeys.length > 0" :bordered="false" class="right-form-wrapper">
          <a-form :form="form" autocomplete="off" class="formStyle" layout="inline">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="分类名称">
                  <a-input
                    v-decorator="[
                      'informationName',
                      {
                        rules: [{ required: true, message: '请输入分类名称!' }],
                      },
                    ]"
                    placeholder="请输入分类名称"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="上级分类">
                  <a-input
                    v-decorator="[
                      'parentInformationName',
                      {
                        rules: [{ required: true, message: '请输入上级分类名称!' }],
                      },
                    ]"
                    :disabled="true"
                    placeholder="请输入上级分类"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item label="排序值">
                  <a-input
                    v-decorator="[
                      'informationOrder',
                      {
                        rules: [{ required: true, message: '请输入排序值!' }],
                      },
                    ]"
                    placeholder="请输入排序值"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row v-show="show_upload" :gutter="24" class="imageUpload">
              <a-col :span="24">
                <a-form-item label="App图标">
                  <a-upload
                    :customRequest="(e) => customRequest(e, 'app_file_list', 'appIconUrl')"
                    :file-list="app_file_list"
                    :remove="(e) => remove(e, 'app_file_list', 'appIconUrl')"
                    :showUploadList="showUploadList"
                    accept="image/png, image/JPG,image/jpeg"
                    class="avatar-uploader"
                    list-type="picture-card"
                    @change="(e) => uploadChange(e, 'app_file_list')"
                  >
                    <div v-if="app_file_list.length < 1">
                      <img alt="" class="pictIcon" src="@/assets/imgs/pict-icon.png" />
                      <p class="imgText">点击上传</p>
                    </div>
                  </a-upload>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row v-show="show_upload" :gutter="24" class="imageUpload">
              <a-col :span="24">
                <a-form-item label="小程序图标">
                  <a-upload
                    :customRequest="(e) => customRequest(e, 'mini_file_list', 'iconUrl')"
                    :file-list="mini_file_list"
                    :remove="(e) => remove(e, 'mini_file_list', 'iconUrl')"
                    :showUploadList="showUploadList"
                    accept="image/png, image/JPG,image/jpeg"
                    class="avatar-uploader"
                    list-type="picture-card"
                    @change="(e) => uploadChange(e, 'mini_file_list')"
                  >
                    <div v-if="mini_file_list.length < 1">
                      <img alt="" class="pictIcon" src="@/assets/imgs/pict-icon.png" />
                      <p class="imgText">点击上传</p>
                    </div>
                  </a-upload>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <div class="anty-form-btn flex justify-center">
            <a-button class="resetBtn" htmlType="button" icon="sync" type="primary" @click="emptyCurrForm">
              重置
            </a-button>
            <a-button
              v-has="'office:edit'"
              class="searchBtn"
              htmlType="button"
              icon="form"
              style="margin-left: 40px"
              type="primary"
              @click="submitCurrForm"
            >
              保存
            </a-button>
          </div>
        </a-card>
        <a-card v-else :bordered="false">
          <a-empty>
            <span slot="description"> 请先选择一个场所分类! </span>
          </a-empty>
        </a-card>
      </div>
    </div>

    <addModal ref="addModal" @success="loadTree" />
  </div>
</template>

<script>
import { uploadFile } from '@/api/api'
import topTitle from '@/components/topTitle'
import { getAction } from '@/api/manage'
import { informationEdit, informationDelete } from '@/api/industry'
import { findEnableDictItemsbyCode } from '@/api/api'
import addModal from './modules/addModel'
export default {
  name: 'placeClassification',
  components: { topTitle, addModal },
  data() {
    return {
      content: [['场所分类']],
      loading: false,
      value: '', // tree search value
      dataList: [],
      dropTrigger: '',
      currSelected: {},
      selectedKeys: [],
      checkedKeys: [],
      departTree: [],
      iExpandedKeys: [],
      checkStrictly: true,
      replaceFields: {
        key: 'id',
        title: 'informationName',
      },
      autoExpandParent: true,

      // 右边
      form: this.$form.createForm(this),
      showUploadList: {
        showPreviewIcon: false,
      },

      appIconUrl: '',
      app_file_list: [],

      iconUrl: '',
      mini_file_list: [],

      show_upload: false,
      imgPrefix: '',

      parentInformationName: '',
    }
  },
  mounted() {
    this.loadTree()
    this.getDist()
  },
  methods: {
    async loadTree() {
      this.loading = true
      let { result } = await getAction('/industry/information/tree')
      this.allTreeKeys = []
      this.departTree = result

      this.getAllKeys(result) // * 用于右下角树操作功能
      this.generateList(this.departTree) // * 用作搜索 书中包含关键字的方法
      this.loading = false
    },

    // * 右键打开菜单
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },

    // * 右键时获取节点信息
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      this.rightClickSelectedKey = node.node.dataRef.id
      this.rightClickSelectedLevel = node.node.dataRef.level
      this.rightClickSelectedInformationName = node.node.dataRef.informationName
    },

    // * 添加
    handleAdd(num) {
      if (num == 2) {
        this.$refs.addModal.show({
          id: this.rightClickSelectedKey,
          level: this.rightClickSelectedLevel,
          parentInformationName: this.rightClickSelectedInformationName,
        })
      } else {
        let id = this.currSelected.id
        let level = this.currSelected.level
        let parentInformationName = this.currSelected.informationName

        this.$refs.addModal.show({ id, level, parentInformationName })
      }
    },

    // * 右键删除
    handleDelete() {
      this.$confirm({
        title: '确认删除',
        content: '确定要删除此分类以及子节点数据吗?',
        onOk: async () => {
          let res = await informationDelete({ id: this.rightClickSelectedKey })
          if (res.code == 200) {
            this.emptyCurrForm()
            this.onClearSelected()
            this.loadTree()
            this.$message.success('删除成功!')
          } else {
            this.$message.warning('删除失败!')
          }
        },
      })
    },

    // * 右键取消
    closeDrop() {
      this.dropTrigger = ''
    },

    // ************************

    // * 清空
    onClearSelected() {
      this.selectedKeys = []
      this.checkedKeys = []
      this.currSelected = {}
      this.form.resetFields()
    },

    // * 用于右下角树操作功能
    getAllKeys(tree) {
      tree.forEach((item) => {
        if (item.id) this.allTreeKeys.push(item.id)
        if (item.children) {
          this.getAllKeys(item.children)
        }
      })
    },

    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },

    closeAll() {
      this.iExpandedKeys = []
    },

    getNodeById(list, id) {
      if (id == '' || id == null) return { informationName: '暂无' }
      for (const item of list) {
        if (item.id === id) return item
        if (item.children) {
          const res = this.getNodeById(item.children, id)
          if (res) return res
        }
      }
    },

    // * 树的筛选方法 开始
    onSearch() {
      const expanded = this.dataList
        .map((item) => {
          if (item.informationName.indexOf(this.value) > -1) {
            return this.getParentKey(item.id, this.departTree)
          }
          return null
        })
        .filter((item, i, self) => {
          if (item && self.indexOf(item) === i) {
            return item
          }
        })
      this.iExpandedKeys = expanded
      this.autoExpandParent = true
    },

    getParentKey(key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentKey = node.id
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children)
          }
        }
      }
      return parentKey
    },

    generateList(tree) {
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        const id = node.id
        const informationName = node.informationName
        this.dataList.push({
          id,
          informationName: informationName,
        })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    // * 树的筛选方法 结束

    // * 树方法
    onCheck(checkedKeys, info) {},

    onSelect(selectedKeys, info) {
      let record = info.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = record
      this.checkedKeys = [record.id] // ! 设置勾选
      this.selectedKeys = [record.id]

      this.setValuesToForm(record)
    },

    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    // * 触发onSelect事件时,为区域树右侧的form表单赋值
    async setValuesToForm(record) {
      const { result } = await getAction('/industry/information/find_parent_info', {
        id: record.id,
      })
      record.parentInformationName = result.name
      this.parentInformationName = result.name

      this.show_upload = false

      if (record.level == 1) {
        this.show_upload = true
        this.iconUrl = record.iconUrl
        this.mini_file_list = [
          {
            uid: 1,
            name: record.iconUrl,
            status: 'done',
            url: this.imgPrefix + record.iconUrl,
          },
        ]

        this.appIconUrl = record.appIconUrl
        this.app_file_list = [
          {
            uid: 1,
            name: record.appIconUrl,
            status: 'done',
            url: this.imgPrefix + record.appIconUrl,
          },
        ]
      }

      this.$nextTick(() => {
        this.form.setFieldsValue({ ...record })
      })
    },

    // ******************************** 表单方法 ********************************
    uploadChange(info, list) {
      info.file.status = 'done'
      this[list] = info.fileList
    },

    remove(list, url) {
      this[url] = ''
      this[list] = []
    },

    async customRequest(info, list, url) {
      let file = info.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 5)
      let res = await uploadFile(formData)

      if (res.code == 200) {
        if (url == 'appIconUrl') {
          this.appIconUrl = res.result.halfPath
        } else if (url == 'iconUrl') {
          this.iconUrl = res.result.halfPath
        }
      }
    },

    // * 右侧表单的事件
    emptyCurrForm() {
      this.form.resetFields()
      this.appIconUrl = ''
      this.iconUrl = ''
      this.app_file_list = []
      this.mini_file_list = []
      // this.selectedKeys = []

      this.form.setFieldsValue({ parentInformationName: this.parentInformationName })
    },

    submitCurrForm() {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          values.id = this.currSelected.id
          values.iconUrl = this.iconUrl
          values.appIconUrl = this.appIconUrl
          let res = await informationEdit(values)
          if (res.code == 200) {
            this.$message.success('保存成功!')
            this.loadTree()
          } else {
            this.$message.error(res.message)
          }
        }
      })
    },

    async getDist() {
      let res = await findEnableDictItemsbyCode({ code: 'static_server' })
      this.imgPrefix = res.result[0].value
    },
  },
}
</script>

<style lang="less" scoped>
.app-container {
  background: var(--theme-content-bg);
  padding-top: 0;

  .bg-common-card {
    background: var(--theme-container-bg);
  }

  .m-h-0 {
    min-height: 0;
  }

  .left-tree-wrap {
    position: relative;
    margin-right: 0.1rem;

    .btn-group {
      padding: 0.2rem 0 0 0.2rem;
      .btn-common {
        width: 1.2rem;
        height: 0.4rem;
        line-height: 0.4rem;
        text-align: center;
        background: #1388ff;
        border-radius: 0.04rem;
        font-size: 0.16rem;
        font-weight: bold;
        color: #0b3f73;
        cursor: pointer;
        &:nth-child(2) {
          margin-left: 0.2rem;
        }
      }
    }

    .drawer-bootom-button {
      position: absolute;
      right: 0.1rem;
      bottom: 0.1rem;
      border-radius: 0.04rem;
    }
  }

  .tree-wrap {
    padding: 0 0.2rem;
    overflow-y: scroll;
  }

  /deep/ .ant-card {
    background: var(--theme-container-bg);
    color: #1163b8;
  }

  .imageUpload {
    margin-bottom: 80px;
    /deep/.avatar-uploader {
      margin-left: 5px;
      > .ant-upload {
        width: 120px;
        height: 120px;
        background: var(--theme-container-bg);
        border: 1px solid var(--theme-input-border);
      }
    }

    /deep/.ant-upload-select-picture-card {
      width: 120px;
      height: 120px;
    }

    /deep/ .ant-upload-list-item {
      width: 120px;
      height: 120px;
    }

    .imgText {
      color: #1163b8;
      font-weight: 500;
    }

    .pictIcon {
      margin-bottom: 10px;
      width: 42px;
      height: 38px;
    }
  }
}
</style>
